package com.fyb.middleware.db.router.config;

import com.fyb.middleware.db.router.DBRouterBase;
import com.fyb.middleware.db.router.DBRouterConfig;
import com.fyb.middleware.db.router.util.PropertyUtil;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author：MR.FANG
 * @name：DataSourceAutoConfig
 * @Date：2025/6/10 下午1:47
 */
@Configuration
public class DataSourceAutoConfig implements EnvironmentAware {

    private Map<String, Map<String,Object>> dataSourceMap = new HashMap<>();

    private int dbCount; //分库数
    private int tbCount;//分表数

    @Bean
    public DBRouterConfig dbRouterConfig(){
        return new DBRouterConfig(dbCount,tbCount);
    }


    @Override
    public void setEnvironment(Environment environment) {
        String prefix = "router.jdbc.datasource.";

        dbCount = Integer.valueOf(environment.getProperty(prefix + "dbCount"));
        tbCount = Integer.valueOf(environment.getProperty(prefix + "tbCount"));

        String dataSources = environment.getProperty(prefix + "list");

        for (String dbInfo : dataSources.split(",")) {
            Map<String,Object> dataSourceProps = PropertyUtil.handle(environment, prefix + dbInfo, Map.class);
            dataSourceMap.put(dbInfo,dataSourceProps);
        }
    }
}
